
import unittest
import anydbm

import helper.person as person

class TestDbm(unittest.TestCase):
    
    def test_sample(self):
        
        src_persons = [person.Person(x,"name-%d"%x) for x in range(3)]
        dbname = "data/test_dbm.db"
        
        # =============== write
        dbwriter = anydbm.open(dbname,"c")
        try:
            for aperson in src_persons:
                # chekanote: to use anydbm, the key can only be string
                dbwriter[aperson._name] = person.StructPackSerializer.serialize(aperson)
        finally:
            dbwriter.close()
            
        # =============== read
        cpy_persons = []
        
        dbreader = anydbm.open(dbname,"c") 
        try:
            for binimage in dbreader.itervalues():
                aperson = person.StructPackSerializer.deserialize(binimage)
                cpy_persons.append(aperson)
        finally:
            dbreader.close()
                
        # =============== check
        cpy_persons.sort(key = lambda x : x._ssn)
        self.assertEqual(src_persons,cpy_persons)
                
if __name__ == "__main__":
    unittest.main()